import { AtButton, AtTag, AtFloatLayout, AtIcon, AtList, AtListItem, AtMessage, AtInput } from "taro-ui";
import { useCommonStore } from "@/store";
import Taro from "@tarojs/taro";
import { View, Image, Text, Picker, Label } from "@tarojs/components";
import { useEffect, useState } from "react";
import { employeeOrderList, progressOrder, searchOrderByDate } from "@/api/order";
import { progressAppointment } from "@/api/appointment";
import { uploadTransfer } from "@/api/transfer";

const EmployeeOrder = () => {
    const commonStore = useCommonStore();

    const [orderInfoOpen, setOrderInfoOpen] = useState<boolean>(false);
    const [startDateSel, setStartDateSel] = useState<string>("");
    const [endDateSel, setEndDateSel] = useState<string>("");

    const [showTransfer, setShowTransfer] = useState<boolean>(false);
    const [amount, setAmount] = useState<number>(0);

    const changeStartDate = (e: any) => setStartDateSel(e.target.value);
    const changeEndDate = (e: any) => setEndDateSel(e.target.value);

    const fetchOrders = async () => {
        const { data } = await employeeOrderList();
        setOrderList(data);
    }

    useEffect(() => {
        commonStore.setSelectedIndex(0);
        fetchOrders();
    }, [])

    Taro.usePullDownRefresh(() => fetchOrders());

    const [orderList, setOrderList] = useState<EmployeeOrderType[]>([]);

    const searchOrders = async () => {
        const { data } = await searchOrderByDate(startDateSel, endDateSel);
        setOrderList(data);
    }

    const initTransferFile = "https://pic.616pic.com/ys_bnew_img/00/08/49/YRcinUFMBS.jpg";
    const [transferFile, setTransferFile] = useState<string>(initTransferFile);
    const changeAmount = (value: number) => setAmount(value);

    const uploadTransferData = async (orderId: number, amount: number, fromTo: number, transferTo: number) => {
        const data = await uploadTransfer({ orderId, amount, transferPic: transferFile, fromTo, transferTo });
        if (data.statusCode === 200) {
            Taro.atMessage({
                type: "success",
                message: "操作成功",
                duration: 1000
            })
            setShowTransfer(false);
            setAmount(0);
            setTransferFile(initTransferFile);
        }
    }

    const renderOrderItem = (item: EmployeeOrderType) => (
        <View key={item.id} className='flex flex-col px-3 py-2 rounded-md bg-white' onLongPress={() => setShowTransfer(true)}>
            <View className='flex gap-x-5 items-center'>
                <Image src={item.servicePic} className='h-24 w-24 rounded-md flex-shrink-0' />
                <View className='flex flex-col w-full'>
                    <View className='flex gap-x-3 items-center'>
                        <Text className='text-[#6190E8] text-xs font-semibold'>下单客户</Text>
                        <Text className='text-sm'>{item.customerName}</Text>
                    </View>
                    <View className='flex gap-x-3 items-center'>
                        <Text className='text-[#6190E8] text-xs font-semibold'>付款</Text>
                        <Text className='text-sm'>{item.price} 元</Text>
                    </View>

                    <View className='w-full'>
                        <AtTag size='small' className='flex-shrink-0' customStyle={
                            item.status === 'pending' ?
                                { color: "white", background: "#FF7F50", fontWeight: "bold" } :
                                item.status === "progress" ?
                                    { color: "white", background: "#FF6347", fontWeight: "bold" } :
                                    { color: "white", background: "#32CD32", fontWeight: "bold" }}
                        >
                            {
                                item.status === 'pending' ? '待服务' :
                                    item.status === 'progress' ? '进行中' :
                                        item.status === 'completed' ? '已完成' :
                                            ''
                            }
                        </AtTag>

                        <View className='mt-2 text-xs flex gap-x-3'>
                            <Text className='text-[#6190E8] font-semibold'>下单时间</Text>
                            <Text>{item.startTime}</Text>
                        </View>

                        <View className='flex justify-around items-center mt-4'>
                            <AtButton size="small" onClick={() => setOrderInfoOpen(true)}>联系客户</AtButton>

                            <AtButton size='small' type="primary" disabled={item.status === "progress"} onClick={async () => {
                                let data: BaseResponse<string>;
                                if (item.orderType) {
                                    data = await progressOrder(item.id);
                                } else {
                                    data = await progressAppointment(item.id);
                                }
                                if (data.code === 200) {
                                    fetchOrders();
                                    Taro.atMessage({
                                        type: "success",
                                        message: "提交成功",
                                        duration: 1000
                                    })
                                }
                            }}
                            >
                                {item.status === 'pending' ? <Text>开始服务</Text> : <Text>服务中</Text>}
                            </AtButton>
                        </View>
                    </View>

                </View>

                <AtFloatLayout isOpened={showTransfer} title="上传垫付证明"
                    onClose={() => {
                        setShowTransfer(false);
                        setAmount(0);
                        setTransferFile(initTransferFile);
                    }}>
                    <View className="flex flex-col justify-cneter">
                        <View className="flex gap-x-3">
                            <Image src={transferFile} className="w-32 h-32 rounded-md flex-shrink-0" onClick={() => Taro.chooseImage({
                                count: 1,
                                sizeType: ['original', 'compressed'],
                                sourceType: ['album', 'camera'],
                                success: (res) => setTransferFile(res.tempFilePaths[0])
                            })} />
                            <View className="flex flex-col justify-between w-full">
                                <Label className="flex items-center justify-center">
                                    <Text className="text-sm flex-shrink-0">垫付金额: </Text>
                                    <AtInput required type="number" value={String(amount)} onChange={changeAmount} name={"amount"} placeholder="请输入垫付金额" />
                                    <Text className="font-semibold">元</Text>
                                </Label>
                                <AtButton type="primary" onClick={() => uploadTransferData(item.id, amount, item.customerId, item.worker)}>上传</AtButton>
                            </View>
                        </View>
                    </View>
                </AtFloatLayout>
            </View >

            <View className='flex gap-x-3 overflow-x-auto items-center mt-2'>
                <Text className='text-[#6190E8] text-xs font-semibold flex-shrink-0'>下单地址</Text>
                <Text className='text-sm address'>{item.address}</Text>
            </View>

            <AtFloatLayout isOpened={orderInfoOpen} title="订单详细" onClose={() => setOrderInfoOpen(false)}>
                <View className="flex justify-between h-full w-full">
                    <View className="flex-shrink-0">
                        <Image src={item.customerAvatar} className="h-20 w-20 rounded-md" />
                    </View>
                    <View className="flex items-center gap-x-3">
                        <Text className="font-semibold">客户联系电话</Text>
                        {item.phone}
                        <AtIcon value="phone" size={18} onClick={() => {
                            Taro.makePhoneCall({ phoneNumber: item.phone });
                        }} />
                    </View>
                </View>
            </AtFloatLayout>
        </View >
    );

    return (
        <View className='overflow-auto p-5 bg-gray-100 flex flex-col gap-y-2 pb-20' style={{ height: "100vh" }}>
            <View>

                <Picker mode='date' value={startDateSel} onChange={changeStartDate}>
                    <AtList>
                        <AtListItem title='请选择起始日期' extraText={startDateSel} />
                    </AtList>
                </Picker>
                <Picker mode='date' value={endDateSel} onChange={changeEndDate}>
                    <AtList>
                        <AtListItem title='请选择截止日期' extraText={endDateSel} />
                    </AtList>
                </Picker>
                <AtButton type="primary" size="small" onClick={searchOrders}>搜索</AtButton>
            </View>

            {
                orderList.length === 0
                    ?
                    <View className='text-2xl font-bold text-[#6190E8] text-center'>暂无订单</View>
                    :
                    orderList.map(item => renderOrderItem(item))
            }

            <AtMessage />
        </View>
    )
}

export default EmployeeOrder;